package com.example.myapplication;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;
import com.example.myapplication.data.model.NewsArticle;
import com.example.myapplication.data.model.NewsResponse;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NewsFragment extends Fragment implements NewsAdapter.OnItemClickListener {

    private static final String TAG = "NewsFragment";
    private RecyclerView newsRecyclerView;
    private NewsAdapter newsAdapter;
    private List<NewsArticle> newsArticles = new ArrayList<>();

    private final OkHttpClient client = new OkHttpClient();
    private final Gson gson = new Gson();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_news, container, false);

        newsRecyclerView = root.findViewById(R.id.news_recycler_view);
        newsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        newsAdapter = new NewsAdapter(newsArticles, this);
        newsRecyclerView.setAdapter(newsAdapter);

        fetchNews();

        return root;
    }

    private void fetchNews() {
        String url = "http://apis.juhe.cn/fapigx/huabian/query?key=344ff29535eb2a9a8d9da9491df2439c&num=10";

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "Failed to fetch news: " + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();
                    NewsResponse newsResponse = gson.fromJson(responseBody, NewsResponse.class);

                    if (newsResponse != null && newsResponse.getResult() != null && newsResponse.getResult().getNewslist() != null) {
                        requireActivity().runOnUiThread(() -> {
                            newsArticles.clear();
                            newsArticles.addAll(newsResponse.getResult().getNewslist());
                            newsAdapter.notifyDataSetChanged();
                        });
                    } else {
                        Log.e(TAG, "News response is null or data is empty.");
                    }
                } else {
                    Log.e(TAG, "Failed to fetch news: " + response.code() + " " + response.message());
                }
            }
        });
    }

    @Override
    public void onItemClick(NewsArticle newsArticle) {
        NavController navController = Navigation.findNavController(requireView());
        Bundle bundle = new Bundle();
        bundle.putString("news_title", newsArticle.getTitle());
        bundle.putString("news_date", newsArticle.getCtime());
        bundle.putString("news_url", newsArticle.getUrl());
        navController.navigate(R.id.action_nav_news_to_newsDetailFragment, bundle);
    }
}